package com.wwj.utils.poi;

import com.wwj.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * Created by Auser on 2016/6/16.
 */
public class CommonExcelView extends AbstractExcelView {

    private int strNum;
    public CommonExcelView(int strNum){
        this.strNum = strNum;
    }

    /**
     *
     * @param model
     *      传入的数据
     * @param workbook
     * @param request
     * @param response
     * @throws Exception
     */
    @Override
    protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
        OutputStream fos = null;
        try {
            //1. 提取数据
            List<List<String>> dataSet = (List<List<String>>) model.get(ExcelUtil.DATA_SET);
            String name = (String) model.get(ExcelUtil.NAME);
            String modelPath = (String) model.get(ExcelUtil.MODEL_PATH);

            //2. 设置输出文件名
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((name).getBytes("utf-8"),"iso8859-1"));

            //3. 创建Sheet
            HSSFWorkbook wk = ExcelUtil.getModelWorkbook(modelPath);
            HSSFSheet sheet = wk.getSheet("sheet1");
            HSSFCell cell;
            int size = dataSet.size();
            for (int i = 0; i < size; i++) { //遍历行
                List<String> record = dataSet.get(i);
                for (int ri = 0; ri < record.size(); ri++) {
                    Object cellValue = record.get(ri);
                    cell = getCell(sheet, i + strNum, ri);
                    if(cellValue instanceof String){
                        setText(cell, cellValue.toString());
                    }else if(cellValue instanceof Double || cellValue instanceof Integer){
                        cell.setCellValue(Double.valueOf(cellValue.toString()));
                    }else if(null == cellValue){
                        cell.setCellValue("");
                    }
                }
            }
            fos = response.getOutputStream();
            wk.write(fos);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null != fos) {
                fos.flush();
                fos.close();
            }
        }
        response.getWriter().write("true");
        response.getWriter().flush();
    }
}
